package com.example.turncardapp

import android.content.Intent
import android.graphics.Color
import android.os.Bundle
import android.view.View
import android.widget.Button
import android.widget.TextView
import android.widget.Toast
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.edit
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import androidx.core.view.children
import com.example.turncardapp.model.CardMatchingGame


class MainActivity3 : AppCompatActivity(), View.OnClickListener {
    lateinit var game: CardMatchingGame
    val cardButtons = mutableListOf<Button>()
    lateinit var score: TextView
    lateinit var exitBtn: Button

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        setContentView(R.layout.activity_main3)
        val gridLayout = findViewById<androidx.gridlayout.widget.GridLayout>(R.id.gridLayout)
        for (v in gridLayout.children){
            if (v is Button){
                v.setOnClickListener(this)
                cardButtons.add(v)
            }
        }

        score = findViewById<TextView>(R.id.score)

        game = CardMatchingGame(cardButtons.count())
        updateUI()

        val reset = findViewById<Button>(R.id.reset)
        reset.setOnClickListener {
            game = CardMatchingGame(cardButtons.count())
            updateUI()
        }

        exitBtn = findViewById(R.id.exit)
        exitBtn.setOnClickListener {
            // compare current game score against stored max and update if needed, then return
            val prefs = getSharedPreferences("game_prefs", MODE_PRIVATE)
            val storedMax = prefs.getInt("game_max_score", 0)
            val newMax = if (game.score > storedMax) {
                prefs.edit { putInt("game_max_score", game.score) }
                game.score
            } else {
                storedMax
            }
            val result = Intent().apply { putExtra("maxScore", newMax) }
            setResult(RESULT_OK, result)
            finish()
        }

        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main)) { v, insets ->
            val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars())
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom)
            insets
        }
    }


    fun updateUI() {
        for(button in cardButtons) {
             val index = cardButtons.indexOf(button)
             val card = game.cardAtIndex(index)

             // disable button if matched
             button.isEnabled = !card.isMatched

             if (card.isChosen) {
                 // show rank and suit
                 button.text = card.toString()
                 // 翻开时使用白色背景（恢复之前的行为）
                 button.setBackgroundColor(Color.WHITE)
                 // set text color depending on suit (hearts/diamonds red)
                 val suit = card.suit
                 if (suit == "♥" || suit == "♦") {
                     button.setTextColor(Color.RED)
                 } else {
                     button.setTextColor(Color.BLACK)
                 }
             } else {
                 button.text = ""
                 // 未翻开时使用你的图片资源 sicnu_bg
                 button.setBackgroundResource(R.drawable.sicnu_bg)
                 // reset text color to default (black)
                 button.setTextColor(Color.BLACK)
             }
        }
        // use formatted string resource for localized score display
        score.text = getString(R.string.score_format, game.score)

        // If all cards are matched, game over -> update stored max score
        val allMatched = (0 until cardButtons.size).all { i -> game.cardAtIndex(i).isMatched }
        if (allMatched) {
            val prefs = getSharedPreferences("game_prefs", MODE_PRIVATE)
            val currentMax = prefs.getInt("game_max_score", 0)
            if (game.score > currentMax) {
                prefs.edit { putInt("game_max_score", game.score) }
                Toast.makeText(this, "恭喜！刷新最高得分：${game.score}", Toast.LENGTH_SHORT).show()
            } else {
                Toast.makeText(this, "游戏结束，得分：${game.score}", Toast.LENGTH_SHORT).show()
            }
        }
    }


    override fun onClick(v: View?) {
        if (v is Button) {
            val index = cardButtons.indexOf(v)
            game.chooseCardAtIndex(index)
            updateUI()
        }
    }
}